<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Session;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;

abstract class HomeController extends Controller
{
    use DispatchesJobs, ValidatesRequests;
    
    public function __construct(\Illuminate\Http\Request $request) {
        Session::put('home', \App\Models\User::find(1));
        Session::save();
        
        if(!session('home')) {
            if ($request->has('code')) {
                $user = \App\Models\User::regUser($request->input('code'));
                if (!$user) {
                    return redirect('home/index/index?ptype=1');
                }
                Session::put('home', $user);
                Session::save();
            }else {
                $appid          = env('WECHAT_APPID');
                $redirect_uri = urlencode($request->url());
                $url = $this->__CreateOauthUrlForCode($redirect_uri);
                header("Location: $url");
                exit();
            }
        }
    }
    private function __CreateOauthUrlForCode($redirectUrl){
		$urlObj["appid"] = env('WECHAT_APPID');
		$urlObj["redirect_uri"] = "$redirectUrl";
		$urlObj["response_type"] = "code";
		$urlObj["scope"] = "snsapi_base";
		$urlObj["state"] = "STATE"."#wechat_redirect";
		$bizString = $this->ToUrlParams($urlObj);
		return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    private function ToUrlParams($urlObj){
		$buff = "";
		foreach ($urlObj as $k => $v){
                    if($k != "sign"){
                        $buff .= $k . "=" . $v . "&";
                    }
                }
		
		$buff = trim($buff, "&");
		return $buff;
    }
}
